/*
 * @Author: sunzhijun 
 * @Date: 2019-04-18 14:41:14 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-03-20 14:33:36
 */
import {promptBox, toast, cacheTools, base} from 'nc-lightapp-front';
import CommonAction from './common';
import do_print from 'src/hrpub/common/utils/print';
// import nodeRefs from '../container/functions/nodeRefs';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import renderPhotoItem from '../container/functions/renderPhoto';
import nodeRefs from '../container/functions/nodeRefs';

export default class TableAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
    }

    //获取表格高度
    getTableHeight = () => {
        const mainTable = document.getElementsByClassName('left');
        let tableHeight = 0;
        if (mainTable[0]) {
            tableHeight = mainTable[0].clientHeight - 92
        }
        this.dispatch({
            type: 'main/update',
            payload: {
                tableHeight: tableHeight
            }
        })
        return tableHeight;
    };

    // 获取主表数据或者刷新
    getMainTableData = async (conditions) => {
        const {props, action} = this.comp;
        const {dispatch, editTable, main, button} = props;
        const {language, pageInfo} = main;
        let conditionsData = !!conditions ? conditions : main.conditions;
        if (!!main.oid) {
            let res = await dispatch({
                type: 'main/getPersonnelData',
                payload: {
                    querycondition: {
                        logic: 'and',
                        conditions: []
                    },
                    oid: main.oid,
                    queryAreaCode:"query",
                    querytype:"tree",
                    func_type: 5,
                    pk_org: main.pk_org,
                    include_child_psncl: false,
                    show_all_info: false,
                    show_on_job_psn: false,
                    tree_node_id: main.tree_node_id || null,
                    pageInfo: pageInfo,
                    ...conditionsData
                }
            });
            if (res.success) {
                let data = res.data;
                if (!!data) {
                    let poi_list = data.poi_list;
                    let rows = poi_list.rows || [];
                    // let allpks = poi_list.allpks;
                    let pageInfo = poi_list.pageInfo;
                    await dispatch({
                        type: 'main/update',
                        payload: {
                            isVisiblePagination: true,
                            isDisabled: false,
                            pk_psnjob: rows[0].values.pk_psnjob.value,    //默认第一行数据的主键，为终止关系和身故处理准备（这两个不是根据选择checkbox选择数据，而是点击行选择）
                            pageInfo
                        }
                    });
                    // 主表里排序值如果不设置会是9999999，所以需要手动额把它置空
                    rows.forEach((item) => {
                        if (item.values['showorder'].value === '9999999') {
                            item.values['showorder'].value = '';
                        }
                    });
                    action.btnAct.orgButtonDataStatus();
                    editTable.setTableData('poi_list', {rows: rows});
                    editTable.focusRowByIndex('poi_list', 0);
                    // cacheTools.set('allpks', allpks);
                    this.judgeAddSubAction(); //判断是否需要批量设置子集
                } else {
                    await dispatch({
                        type: 'main/update',
                        payload: {
                            isVisiblePagination: false,
                            isDisabled: true
                        }
                    })
                    action.headerAct.setShowOrHidden(false);
                    action.btnAct.orgButtonNoDataStatus();
                    editTable.setTableData('poi_list', {rows: []});
                }
            }
        } else {
            action.btnAct.orgButtonNoDataStatus();
        }
    };

    //设置照片是否可上传
    setIsDisableUpload = (isDisabled) => {
        if(nodeRefs.disableUploadRefs) {
            nodeRefs.disableUploadRefs.setState({
                disableUpload: isDisabled
            })
        }
    }

    deletePersonnelInfo = (record) => {
        const {props, action} = this.comp;
        const {editTable, main} = props;
        const {language} = main;
        let pk_psnjob;
        if (record) {
            pk_psnjob = record.values.pk_psnjob.value
        } else {
            let selectedData = editTable.getCheckedRows('poi_list');
            if (!!selectedData.length) {
                let pk_psnjobArr = [];
                selectedData.map((item) => {
                    pk_psnjobArr.push(item.data.values.pk_psnjob.value);
                })
                pk_psnjob = pk_psnjobArr.join(',');
            } else {
                toast({color: 'danger', content: language['hi6007-000164']}); //请选择要删除的数据!
                return false;
            }
        }
        promptBox({
            color: 'warning',
            title: language['hi6007-000008'], //提示
            content: language['hi6007-000059'], //确定要删除所选数据吗？
            beSureBtnClick: () => {
                this.deletePersonnel(pk_psnjob);
            }
        });
    }
    //删除相关人员信息
    deletePersonnel = async (pk_psnjob,) => {
        const {props, action} = this.comp;
        const {editTable, main} = props;
        const {language} = main;
        let res = await this.dispatch({
            type: 'main/deletePersonnelInfo',
            payload: {
                param_str: pk_psnjob,
                func_type: 5,
                pk_org: main.pk_org
            }
        })
        if (res.success) {
            this.getMainTableData();
            toast({color: 'success', content: language['hi6007-000006']});
        }
    }

    //刷新
    refresh = async () => {
        const {props: {main: {language}}} = this.comp;
        this.getMainTableData();
        toast({color: 'success', content: language['hi6007-000291']});
    }


    //单击行获取行数据
    getTableRowData = async (props, moduleId, record, index) => {
        const {action} = this.comp;
        let {main} = props;
        let pk_psnjob = record && record.values.pk_psnjob.value;
        // action.btnAct.btnStatus(record);
        // console.log(pk_dimension);
        await this.dispatch({
            type: 'main/update',
            payload: {
                // selectedData: record,
                pk_psnjob: pk_psnjob
            }
        });
        if (main.isShowSub) { //isShowSub为true时代表子集已显示
            this.getCardDetailData(pk_psnjob);
            this.changeTab(main.activeKey);
        }
    }

    onSelected = async (props, moduleId, record, index, isSelected) => {
        const {action} = this.comp;
        let {main} = props;
        props.editTable.setClickRowIndex('poi_list', {
            record: record,
            index: index
        });
        props.editTable.focusRowByIndex('poi_list', index);
        let pk_psnjob = record && record.values.pk_psnjob.value;
        await this.dispatch({
            type: 'main/update',
            payload: {
                // selectedData: record,
                pk_psnjob: pk_psnjob
            }
        });
        if (main.isShowSub) { //isShowSub为true时代表子集已显示
            this.getCardDetailData(pk_psnjob);
            this.changeTab(main.activeKey);
        }
    };

    //修改相关人员信息
    editPersonnelInfo = async (record, isEdit) => {
        const {props, action} = this.comp;
        const {cardTable, main} = props;
        let pk_psnjob;
        if (record) {
            pk_psnjob = record.values.pk_psnjob.value;
        } else {
            pk_psnjob = main.pk_psnjob;
            this.setIsDisableUpload(false);
        }
        await this.dispatch({
            type: 'main/update',
            payload: {
                ui_state: 2,
                isEdit: true
            }
        })

        let res = await this.dispatch({
            type: 'main/editPersonnelInfo',
            payload: {
                pk_psnjob: pk_psnjob,
                func_type: 5,
                pk_org: main.pk_org
            }
        })

        if (res.success) {
            if (res.data === 'success') {
                if (main.isCardForm) {
                    action.cardAct.setEditCardStatus();
                } else {
                    this.toCardForm(record);
                }
            }
        }
    }

    /**
     * @param index             索引
     * @param record            数据
     * @memberof toCardForm     进入CardForm
     */
    toCardForm = async (record) => {
        const {props, action} = this.comp;
        const {main} = props;
        const {language, isSort} = main;
        if (isSort) {
            return
        }
        let pk_psnjob = record && record.values.pk_psnjob.value;
        await this.dispatch({
            type: 'main/update',
            payload: {
                isShowSub: false,
                conHeight: '100%',
                isCardForm: true,
                selectedData: record,
                pk_psnjob: pk_psnjob,
                pk_psncl: pk_psnjob,
                subTableEditable: false,
                // cardId: ''
                cardId: 'bd_psndoc'
            }
        });
        action.btnAct.onlyEditButtonStatus();
        this.getCardDetailData(pk_psnjob);
    }

    //请求卡片详情页数据
    /**
     * @param  pk_psnjob    主键
     */
    getCardDetailData = async (pk_psnjob) => {
        const {props, action} = this.comp;
        const {form, main, cardTable, meta} = props;
        const {language, isCardForm, areaCodeList, formLists} = main;
        let res = await this.dispatch({
            type: 'main/queryOneAction',
            payload: {
                func_type: 5,
                pk_org: main.pk_org,
                pk_psnjob: pk_psnjob
            }
        });
        if (res.success) {
            let data = res.data;
            let template = meta.getMeta();
            // let tableList = [];
            if (!!data) {
                let {
                    areaCodeList,
                    allArea,
                    busiSet,
                    image
                } = data;
                let hi_psnjob_h = data.psnjobForm && data.psnjobForm.hi_psnjob_h,
                    hi_psnorg_h = data.psnorgForm && data.psnorgForm.hi_psnorg_h,
                    bd_psndoc = data.psndocForm && data.psndocForm.bd_psndoc,
                    hi_psndoc_cert = data.certGrid && data.certGrid.hi_psndoc_cert;
                // areaCodeList = data.areaCodeList;
                !!areaCodeList.length && areaCodeList.map((item, index) => {
                    template[item] = deepCopy(allArea[item]); //此处做法是为了隔离配置的模板数据，若不如此 createEditTable 会报错误
                    // tableList.push(item);
                })
                meta.setMeta(template);
                await this.dispatch({
                    type: 'main/update',
                    payload: {
                        hi_psnjob_h: hi_psnjob_h,
                        hi_psnorg_h: hi_psnorg_h,
                        bd_psndoc: bd_psndoc,
                        hi_psndoc_cert: hi_psndoc_cert,
                        imageData: image,
                        // cardId: 'bd_psndoc'
                    }
                });
                if (!main.areaCodeList.length) {
                    await this.dispatch({
                        type: 'main/update',
                        payload: {
                            areaCodeList: areaCodeList,
                            busiSet: busiSet
                        }
                    });
                }
                if (isCardForm) {
                    renderPhotoItem.call(this.comp);
                    //设置form 数据，相关人员只有bd_psndoc，下面两条备用
                    form.setAllFormValue({
                        'bd_psndoc': data['psndocForm']['bd_psndoc'],
                        // 'hi_psnjob_h': data['psnjobForm']['hi_psnjob_h'],
                        // 'hi_psnorg_h': data['psnorgForm']['hi_psnorg_h']
                    });
                    cardTable.toggleCardTable(data.areaCodeList, false);
                    cardTable.toggleCardTable('hi_psnjob', true);
                    if (main.isEdit) {
                        action.cardAct.setEditCardStatus();
                        this.setIsDisableUpload(false);
                    } else {
                        this.setIsDisableUpload(true);
                    }
                } else {
                    this.changeTab(main.activeKey, data.areaCodeList);
                }
            } else {
                form.EmptyAllFormValue('bd_psndoc');
                main.areaCodeList.map((item) => {
                    cardTable.setTableData(item, {rows: []}, null, false);
                });
            }
        }
    }

    //打印

    // tempPrint = ()=>{
    //     this.tempPrintFn.call(this,'itemlist');
    // }
    // tempPrintFn = (tableid)=>{
    //     const { props } = this.comp;
    //     const { editTable, meta, main} = props;
    //     const { language } = main;
    //     let allTableList = editTable.getAllRows(tableid);
    //     let template = meta.getMeta()[tableid];
    //     do_print(document.querySelector('#tableListData'), {
    //         title: language['hrp6003-0000011'],
    //         maker: language['hrp6003-000008'],
    //         date:  language['hrp6003-000009'],
    //         beforeAppend: (data) => {
    //             data[0].map((item,index) => {
    //                 let len = item && item.length;
    //                 if(index != 0){
    //                     item[0] = index;
    //                     if( item[4] === true ){
    //                         item[4] = language['hrp6003-0000024']
    //                     }else{
    //                         item[4] = language['hrp6003-0000028']
    //                     }
    //                 }
    //                 item.splice(len-1,1);
    //             });
    //             return data;
    //         }
    //     },{
    //         data: allTableList,
    //         tableTmp: template
    //     })
    // }

    //设置翻页显示隐藏
    setPaginationVisible = async (visible) => {
        await this.dispatch({
            type: 'main/update',
            payload: {
                isVisiblePagination: visible
            }
        });
    }

    //根据页码改变数据
    changePagination = async (pageIndex) => {
        const {props} = this.comp;
        const {main} = props;
        let pageInfo = main.pageInfo;
        pageInfo.pageIndex = pageIndex;
        await this.dispatch({
            type: 'main/update',
            payload: {
                pageInfo
            }
        });
        this.getMainTableData();
    }

    //下拉分页页数
    pageSizeSelect = async (pageSize) => {
        const {props} = this.comp;
        const {main} = props;
        let pageInfo = main.pageInfo;
        pageInfo.pageSize = pageSize;
        await this.dispatch({
            type: 'main/update',
            payload: {
                pageInfo
            }
        });
        this.getMainTableData();
    }

    //选择tab获取子集数据
    changeTab = async (index, areaCodeList) => {
        const {props, action} = this.comp;
        const {main} = props;
        let moduleId = !!main.areaCodeList.length ? main.areaCodeList[index] : areaCodeList[index];
        await this.dispatch({
            type: 'main/update',
            payload: {
                activeKey: index,
                subTableId: moduleId
            }
        })

        action.cardAct.headAngleToggle(props, moduleId, true);
    }

    //显示子集名称
    renderName = (item) => {
        const {props} = this.comp;
        const {meta, main} = props;
        let template = meta.getMeta();
        return (
            template[item].name
        );
    }

    //判断是否需要批量增加子集
    judgeAddSubAction = async () => {
        const {props, action} = this.comp;
        const {main} = props;
        let res = await this.dispatch({
            type: 'main/judgeAddSubAction',
            payload: {
                pk_org: main.pk_org,
                func_type: 5
            }
        })
        if (res.success) {
            let data = res.data;
            action.btnAct.setBatchEditButtonStatus(data);
        }
    }

    //显示子集右侧菜单
    // renderSubMenu = ()=> {
    // const {tableList} = this.state;
    // const {meta, pageHeight} = this.props;
    // let template = meta.getMeta();
    // const { props } = this.comp;
    // const {NCTabs, NCMenu, NCIcon} = base;
    // const {NCSubMenu, Item} = NCMenu;
    // let { main } = props;
    // return (
    //     <div className="sub-set-menu-wrapper">
    //         <NCMenu
    //             mode="vertical"
    //             className="sub-set-menu"
    //             // onClick={this.quickClickItem}
    //             onOpenChange={(e) => {
    //                 setTimeout(() => {
    //                     let subDom = nodeRefs.refs.querySelector('.u-menu-sub');
    //                     subDom.style.height = parseInt(main.footerHeight) - 2 + 'px';
    //                 },1);
    //             }}
    //         >
    //             <NCSubMenu
    //                 title={<NCIcon type="uf-symlist" />}
    //                 className="sub-set-submenu"
    //             >
    //                 {/* {tableList.map((item) => {
    //                     return ( */}
    //                         <Item
    //                             // key={item}
    //                         >
    //                             <a href="javascript:void(0)">
    //                                 {/* {template[item].name} */}
    //                                 神奇的舞蹈
    //                             </a>
    //                         </Item>
    //                     {/* );
    //                 // })} */}
    //             </NCSubMenu>
    //         </NCMenu>
    //     </div>
    // );
    // }
}